//涉及login的全部内容

import {reactive, ref} from "vue";
import {useStore} from "vuex";
import {useRouter} from 'vue-router'
import {isLogin, login , isLoginData} from "../axios/API";
import {ElMessage} from "element-plus";

export default function () {
    //表单内容
    let loginInfo = reactive({
        username: '',
        password: ''
    })
    //表单校验
    let rules = reactive({
        username: [{required: true, message: '请输入用户名', trigger: 'blur'}],
        password: [{required: true, message: '请输入密码', trigger: 'blur'}]
    })
    //表单标记
    let loginForm = ref(null)
    //vuex
    let store = useStore()
    //路由
    let router = useRouter()

    //测试是否登录
    async function testIsLogin() {
        // let {data} = await isLogin()
        // console.log('是否', data)
        console.log('1212', await isLoginData())
    }

    //提交表单方法
    function submitForm() {
        //逆天的写法，我麻了
        loginForm.value.validate( async (valid) => {
            if (valid) {
                //表单校验成功，准备登录
                let {data} = await login(loginInfo)
                if (data.status + '' === '999') {
                    //登录失败
                    ElMessage.error(`登录失败：${data.info}`)
                } else if (data.status + '' === '200') {
                    //登录成功
                    ElMessage.success('登录成功！')
                    //向vuex中保存token
                    store.commit('loginStore/UPDATE_TOKEN', data.token)
                    //向vuex中保存username
                    store.commit('loginStore/UPDATE_USERNAME', loginInfo.username)
                    //路由跳转
                    router.push({
                        name: 'welcome'
                    })
                }
            }
        })
    }

    return {
        loginInfo, rules, loginForm, submitForm, testIsLogin
    }
}
